<template>
  <div class="article-form">
    <el-dialog
      v-loading="loading"
      :title="type + '文章'"
      :visible="show"
      :before-close="onBeforeClose"
      width="100%"
      center
      @open="onOpen"
    >
      <el-form ref="formRef" :model="form" :rules="articleRules">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="文章标题" label-width="80px" prop="title">
                  <el-input v-model="form.title" autocomplete="off" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="文章摘要" label-width="80px" prop="summary">
                  <el-input v-model="form.summary" autocomplete="off" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="文章分类" label-width="80px" prop="category_id">
                  <el-tag v-if="selectCate" class="pointer" type="success" closable @close="onCloseCate">
                    {{ selectCate }}
                  </el-tag>
                  <el-popover v-else placement="bottom" trigger="click" @show="onShowCate">
                    <el-tag
                      v-for="cate in cateList"
                      :key="cate.id"
                      class="mtb-5 pointer"
                      type="success"
                      @click="onSelectCate(cate)"
                    >
                      {{ cate.name }}
                    </el-tag>
                    <el-button slot="reference" size="mini">选择分类</el-button>
                  </el-popover>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="文章标签" label-width="80px" prop="tags">
                  <el-tag
                    v-for="(tag, index) in selectTags"
                    :key="index"
                    class="pointer"
                    type="success"
                    closable
                    @close="onCloseTag(tag)"
                  >{{ tag.name }}</el-tag>
                  <el-popover v-if="selectTags.length !== 3" placement="bottom" trigger="click" @show="onShowTag">
                    <el-tag
                      v-for="tag in tagList"
                      :key="tag.id"
                      class="pointer"
                      type="success"
                      @click="onSelectTag(tag)"
                    >{{ tag.name }}</el-tag>
                    <el-button slot="reference" size="mini">选择标签</el-button>
                  </el-popover>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="文章封面" label-width="80px">
              <image-upload ref="myStaffPhoto" :is-thumbnail="true" @updata-url="onUpdataUrl" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否发布" label-width="80px" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="draft">发布</el-radio>
                <el-radio label="published">草稿</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button @click="onBeforeClose">取 消</el-button>
            <el-button type="primary" @click="onSubmit">确 定</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="文章内容" label-width="80px" prop="content">
              <div style="border: 1px solid #ccc">
                <Toolbar
                  style="border-bottom: 1px solid #ccc"
                  :editor="editor"
                  :default-config="toolbarConfig"
                  :mode="mode"
                />
                <Editor
                  v-model="form.content"
                  style="height: 500px; overflow-y: hidden"
                  :default-config="editorConfig"
                  :mode="mode"
                  @onCreated="onCreated"
                />
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云
const cos = new COS({
  SecretId: 'AKIDKUO2PVKtCDxSgeKfla8PQAdplRpwnOhk', // 身份识别 ID
  SecretKey: 'nKaZHjuoWx70c2C5h26vTkkTv61f28xV' // 身份密钥
})
import { articleRules } from '@/utils/rules'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getCateListAPI } from '@/api/cate'
import '@wangeditor/editor/dist/css/style.css'
import { getTagListAPI } from '@/api/tag'
import { addArticleAPI, getArticleAPI, putArticleAPI } from '@/api/article'
export default {
  components: { Editor, Toolbar },
  props: {
    show: {
      type: Boolean,
      required: true
    },
    type: {
      type: String,
      required: true
    },
    currArticleId: {
      type: Number,
      required: false,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      form: {
        title: '',
        content: '',
        category_id: '',
        summary: '',
        status: '',
        thumbnail: '',
        tags: []
      },
      articleRules,
      selectCate: '',
      cateList: [],
      selectTags: [],
      tagList: [],
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          // 上传图片
          uploadImage: {
            maxFileSize: 1 * 1024 * 1024,
            maxNumberOfFiles: 5,
            allowedFileTypes: ['image/*'],
            timeout: 5 * 1000,
            customUpload(file, insertFn) {
              // 执行上传操作 上传到cos
              cos.putObject(
                {
                  Bucket: 'jlgl-1313037814',
                  Region: 'ap-guangzhou',
                  Key: file.name,
                  Body: file,
                  StorageClass: 'STANDARD'
                },
                (err, data) => {
                  console.log(err || data)
                  const url = 'http://' + data.Location
                  insertFn(url)
                }
              )
            }
          }
        }
      },
      mode: 'default' // or 'simple'
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onUpdataUrl(url) {
      this.form.thumbnail = url
    },
    async onOpen() {
      if (this.currArticleId) {
        this.loading = true
        const res = await getArticleAPI(this.currArticleId)
        this.form = res.data
        this.selectTags = res.data.tagList
        this.selectCate = res.data.category_name
        if (res.data.thumbnail) {
          this.$refs['myStaffPhoto'].fileList = [
            { url: res.data.thumbnail, upload: true }
          ]
        }
        this.loading = false
      }
    },
    onResetData() {
      this.$refs['formRef'].clearValidate()
      this.form = {
        title: '',
        content: '',
        category_id: '',
        summary: '',
        status: '',
        thumbnail: '',
        tags: []
      }
      this.selectCate = ''
      this.selectTags = []
      this.$refs['myStaffPhoto'].fileList = []
    },
    async onBeforeClose() {
      try {
        await this.$confirm('还有未保存的内容哦确定关闭吗？')
        this.$emit('update:show', false)
        this.onResetData()
      } catch (error) {
        console.log(error)
      }
    },
    async onSubmit() {
      const reg = /\<p\>\<br\>\<\/p\>/g
      this.form.content = this.form.content.replace(reg, '')

      await this.$refs['formRef'].validate(async (valid) => {
        if (valid) {
          if (this.form.id) {
            delete this.form.author_name
            delete this.form.category_name
            delete this.form.createTime
            delete this.form.tagList

            await putArticleAPI(this.form.id, this.form)
            this.$message.success('编辑文章成功')
          } else {
            await addArticleAPI(this.form)
            this.$message.success('新增文章成功')
          }
          this.$emit('update:show', false)
          this.$emit('update-article')
          this.onResetData()
        } else {
          this.$message.error('请填写完整信息')
          return false
        }
      })
    },
    // 显示分类
    async onShowCate() {
      const res = await getCateListAPI()
      this.cateList = res.data.result
    },
    // 选择分类
    onSelectCate(cate) {
      this.form.category_id = cate.id
      this.selectCate = cate.name
    },
    // 取消分类
    onCloseCate() {
      this.form.category_id = null
      this.selectCate = ''
    },
    // 显示标签
    async onShowTag() {
      const res = await getTagListAPI()
      this.tagList = res.data.result
    },
    // 选择标签
    onSelectTag(tag) {
      const boo = this.selectTags.some((item) => item.id === tag.id)
      // 判断标签是否重复
      if (boo) {
        return this.$message.warning('有相同的标签，请重新选择')
      }
      this.form.tags.push(tag.id)
      this.selectTags.push({ id: tag.id, name: tag.name })
    },
    // 取消标签
    onCloseTag(tag) {
      this.form.tags = this.form.tags.filter((item) => item !== tag.id)
      this.selectTags = this.selectTags.filter((item) => item.id !== tag.id)
    }
  }
}
</script>
<style lang="scss" scoped>
.mtb-5 {
  margin: 5px 0;
}

.pointer {
  cursor: pointer;
  margin: 0 5px;
}

.title,
.demo-drawer__footer {
  text-align: center;
}

.demo-drawer__content {
  padding: 0 10px;
}

::v-deep .el-dialog {
  margin-top: 0 !important;
}
</style>
